﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ACtrl : AnimalCtrl
{
    public override void CheckDie()
    {
        //genome.fitness += Time.deltaTime;
        //health -= isActiveSpeed ? Time.deltaTime * (amType == "A" ? 2 : 2) : Time.deltaTime;
        if (health <= 0)
        {
            health = 0;
            gameObject.SetActive(false);
        }
    }
    public override void Run()
    {
        inputs = new double[7];
        inputs[inputs.Length - 1] = health / 50f;

        GameObject food = GetNear("Food");
        GameObject b = GetNear("B");

        if (food == null)
        {
            inputs[0] = 0;
            inputs[1] = 0;
            inputs[2] = 0;
        }
        else
        {
            float af1 = Vector3.Angle(food.transform.position - transform.position, transform.forward) / 180f;
            float af2 = Vector3.Angle(food.transform.position - transform.position, transform.right) / 180f;
            float fdis = Vector3.Distance(transform.position, food.transform.position) / 57f;

            inputs[0] = af1;
            inputs[1] = af2;
            inputs[2] = fdis;
        }
        if (b == null)
        {
            inputs[3] = 0;
            inputs[4] = 0;
            inputs[5] = 0;
        }
        else
        {
            float ab1 = Vector3.Angle(b.transform.position - transform.position, transform.forward) / 180f;
            float ab2 = Vector3.Angle(b.transform.position - transform.position, transform.right) / 180f;
            float bdis = Vector3.Distance(transform.position, b.transform.position) / 57f;

            inputs[3] = ab1;
            inputs[4] = ab2;
            inputs[5] = bdis;
        }
        inputs[6] = isCanJiasu ? 1 : -1;
        double[] outputs = nn.Run(inputs);
        rd.angularVelocity = transform.up * maxTorque * (float)outputs[1];
        if(outputs[2] > 0 && isCanJiasu)
        {
            isCanJiasu = false;
            isActiveSpeed = true;
            genome.fitness -= 1;
        }
        rd.velocity = transform.forward * maxSpeed * (float)outputs[0] * (isActiveSpeed ? (amType == "A" ? 2 : 2) : 1);
    }

    public GameObject GetNear(string tag)
    {
        GameObject[] gos = GameObject.FindGameObjectsWithTag(tag);
        float dis = 999;
        GameObject go = null;
        foreach (var t in gos)
        {
            float d = Vector3.Distance(t.transform.position, transform.position);
            if (d < dis)
            {
                dis = d;
                go = t;
            }
        }
        return go;
    }
}
